import os
from datetime import datetime
from lib2to3.fixes.fix_input import context
from predict import Predict

from flask import Flask, render_template, send_from_directory, redirect, request, jsonify
from mypy.dmypy.client import action
from werkzeug.utils import secure_filename

app = Flask(__name__)
# 配置上传参数
app.config['UPLOAD_FOLDER'] = 'static/image'  # 上传目录
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB 限制
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}  # 允许的扩展名

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

def allowed_file(filename):
    """验证文件扩展名是否合法"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

# @app.route('/',methods=['get'])
# def hello_world():  # put application's code here
#     return render_template('index.html')


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 检查是否有文件被上传
        if 'file' not in request.files:
            return redirect(request.url)

        file = request.files['file']

        # 如果没有选择文件
        if file.filename == '':
            return redirect(request.url)

        # 验证文件合法性
        if file and allowed_file(file.filename):
            # 安全过滤文件名
            filename = secure_filename(file.filename)
            # 生成唯一文件名（可选）
            # import uuid
            # unique_filename = str(uuid.uuid4()) + '_' + filename
            save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)

            # 保存文件
            file.save(save_path)

            return render_template('demo.html', filename=filename)

    return render_template('demo.html')

@app.route('/test', methods=['GET', 'POST'])
def test_file():

    file_name = request.get_json().get('file_name')
    prediction = Predict()
    data = prediction.recognition(file_name)
    return jsonify(data)

# 用于访问上传后的文件
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run()
